import {
  Component,
  Input,
  OnInit,
  Output,
  EventEmitter,
  ViewChild,
  ElementRef,
  ViewChildren,
  QueryList, Renderer2
} from '@angular/core';



export interface ImageSlider{
  imgUrl:string;
  link:string;
  caption:string;
}

@Component({
  selector: 'app-image-slider',
  templateUrl: './image-slider.component.html',
  styleUrls: ['./image-slider.component.css']
})


/**
 * 接口是可选的，建议有他，这样少写ngOnInit会有提示
 */
export class ImageSliderComponent implements OnInit {

  /**
   * 构造函数永远首先被调用
   */
   constructor(private rd2:Renderer2) {
    console.log("组件构造调用");
   }


  /** 指定属性由外部传入**/
  @Input() sliders:ImageSlider[]=[];
  @Input() sliderHeight="160px";
  @Input() intervalBySeconds=2;


  /** static ngif ngfor 包含之下，true静态的**/
  //在组件类中引用模板元素
  @ViewChild("coolImageSlider",{static:true}) imageSlider: ElementRef;

  //在组件类中引用多个元素
  @ViewChildren("img") images: QueryList<ElementRef> | undefined;
  selectedIndex=0;
  intervalId;

  /**
   * 组件初始化完完成，我们可以安全的使用组件的属性和方法
   */
  ngOnInit(): void {
    console.log("组件初始化");
    console.log(this.imageSlider);
    // // @ts-ignore  修改引用的html的内容
    // this.imageSlider.nativeElement.innerHTML="sdfsdfsdfsdfsdfsdf测试";
    console.log(this.images)
  }

  ngAfterViewInit():void{     //ngAfterViewInit 一定行
    // console.log(this.images)
    // this.images?.forEach(item => {
    //   item.nativeElement.style="width:100%"
    // })
    this.intervalId=setInterval(()=>{
      this.rd2.setProperty(this.imageSlider.nativeElement,'scrollLeft',
        this.getIndex(++this.selectedIndex%this.sliders.length) * this.imageSlider.nativeElement.scrollWidth/this.sliders.length);
    },this.intervalBySeconds*1000)
  }

  ngOnDestroy():void{
    clearInterval(this.intervalId);
  }

  getIndex(idx:number):number{
    return idx>=0
      ? idx%this.sliders.length
      :this.sliders.length-Math.abs(idx)%this.sliders.length;
  }

  handleScroll(ev:any){
   const  ratio= ev.target.scrollLeft*this.sliders.length/ev.target.scrollWidth;
   this.selectedIndex=Math.round(ratio);
  }

}
